package com.tzxs.pay.main.first;

import android.Manifest;
import android.annotation.SuppressLint;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tzxs.pay.R;
import com.tzxs.pay.databinding.FragmentFirstBinding;
import com.tzxs.pay.main.BaseFragment;
import com.tzxs.pay.main.bill.detail.AutTncActivity;
import com.tzxs.pay.main.bill.detail.AutTradedDetailActivity;
import com.tzxs.pay.main.bill.detail.CollAndInstallDetailActivity;
import com.tzxs.pay.main.bill.model.AutBeanDetail;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.deposit.DepositStActivity;
import com.tzxs.pay.main.first.goods.GoodsMangeActivity;
import com.tzxs.pay.main.first.handover.HandOverActivity;
import com.tzxs.pay.main.first.model.NoticeBean;
import com.tzxs.pay.main.gather.DepositActivity;
import com.tzxs.pay.main.gather.GeneralActivity;
import com.tzxs.pay.main.goods.GoodsGaActivity;
import com.tzxs.pay.main.installment.InstallmentActivity;
import com.tzxs.pay.main.login.LoginViewModel;
import com.tzxs.pay.main.mine.signing.SigningManageActivity;
import com.tzxs.pay.main.onlineaut.OnlineAutActivity;
import com.tzxs.pay.main.print.PrintAllActivity;
import com.tzxs.pay.util.ISharedPreference;
import com.tzxs.pay.util.ScanActivity;
import com.tzxs.pay.util.viewmodel.Callback;
import com.uuzuche.lib_zxing.activity.CodeUtils;

/**
 * Created by zfc on 2018/3/29.
 * 首页
 */
public class FirstFragment extends BaseFragment<FragmentFirstBinding> implements View.OnClickListener {

    private RxPermissions permissions;
    private static final int SCAN_CODE = 100;//二维码扫描
    private static final String TAG = FirstFragment.class.getSimpleName();
    private BillViewModel model;
    private LoginViewModel loginViewModel;

    @Override
    public int getContentLayoutId() {
        return R.layout.fragment_first;
    }

    @Override
    protected void viewCreate(Bundle savedInstanceState) {
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        //权限
        permissions = new RxPermissions(getActivity());
        showNotice();
        binding.firstGather.setOnClickListener(this);
        binding.firstDeposit.setOnClickListener(this);
        binding.firstInstallment.setOnClickListener(this);
        binding.firstStatistics.setOnClickListener(this);
        binding.firstGathering.setOnClickListener(this);
        binding.firstPrintAll.setOnClickListener(this);
        binding.firstScan.setOnClickListener(this);
        binding.firstOnlineAut.setOnClickListener(this);
        binding.manageOrder.setOnClickListener(this);
        binding.handover.setOnClickListener(this);
        binding.signManage.setOnClickListener(this);
        binding.setViewModel(model);
        //获取首页的统计
        model.getFirstPageData(() -> {
        });
        loginViewModel.getNoticeList(0, 10, new Callback() {
            @Override
            public void success() {
                binding.constraintLayoutTongzhi.setVisibility(View.VISIBLE);
            }
        });
        model.snackbarText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s != null) {
                    Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
                }
            }
        });
        //点击事件
        binding.noticeMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PendingMsgActivity.class);
                startActivity(intent);
            }
        });
        binding.pendingOrderMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PendingMsgActivity.class);
                startActivity(intent);
            }
        });
        //过期订单的跳转
        binding.constraintLayoutTongzhi.setOnClickListener(view -> {
            Intent intent = new Intent(getContext(), PendingMsgActivity.class);
            startActivity(intent);
        });
    }

    //显示 通知消息
    private void showNotice() {
        if (getActivity() == null) {
            return;
        }
        if (model.noticeBeans.get() == null) {
            String noticeStr = ISharedPreference.getInstance(getActivity().getApplication()).getNoticeStr();
            if (TextUtils.isEmpty(noticeStr)) {
                return;//如果为空不用管
            }
            Gson gson = new Gson();
            NoticeBean bean = gson.fromJson(noticeStr, new TypeToken<NoticeBean>() {
            }.getType());
            model.noticeBeans.set(bean);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //普通收款
            case R.id.first_gather:
                Intent geIntent = new Intent(getActivity(), GeneralActivity.class);
                startActivity(geIntent);
                break;
            //押金收款
            case R.id.first_deposit:
                Intent deIntent = new Intent(getActivity(), DepositActivity.class);
                startActivity(deIntent);
                break;
            //短息预授权
            case R.id.first_online_aut:
                Intent msgIntent = new Intent(getActivity(), OnlineAutActivity.class);
                startActivity(msgIntent);
                break;
            //分期付款
            case R.id.first_installment:
                Intent intentInstall = new Intent(getActivity(), InstallmentActivity.class);
                startActivity(intentInstall);
                break;
            //押金统计
            case R.id.first_statistics:
                Intent depositSt = new Intent(getActivity(), DepositStActivity.class);
                startActivity(depositSt);
                break;
            //打印汇总
            case R.id.first_print_all:
                Intent printIntent = new Intent(getActivity(), PrintAllActivity.class);
                startActivity(printIntent);
                break;
            //扫一扫
            case R.id.first_scan:
                requestScanPermission();
                break;
            //商品管理  暂定
            case R.id.manage_order:
                Intent shoppingIntent = new Intent(getActivity(), GoodsMangeActivity.class);
                startActivity(shoppingIntent);
                break;
            //商品收款
            case R.id.first_gathering:
                Intent statisticsIntent = new Intent(getActivity(), GoodsGaActivity.class);
                startActivity(statisticsIntent);
                break;
            //签约管理
            case R.id.sign_manage:
                Intent signIntent = new Intent(getActivity(), SigningManageActivity.class);
                startActivity(signIntent);
                break;
            //交接班
            case R.id.handover:
                Intent handIntent = new Intent(getActivity(), HandOverActivity.class);
                startActivity(handIntent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SCAN_CODE) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result == null) {
                        return;
                    }
                    boolean strHead = result.contains("fu");
                    Log.d(TAG, "onActivityResult: 小票抬头是fu开头：" + strHead + "结果:" + result);
                    if (result.startsWith("fu")) {//当时预授权订单时
                        //判断是否存在 订单
                        model.getAutBillDetail(result, () -> {
                            AutBeanDetail.DataBean beanDetail = model.autDeatil.get();
                            if (beanDetail == null) {
                                Toast.makeText(getContext(), "该订单为空", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (beanDetail.getPay_status() == 1) {
                                Intent intent = new Intent(getContext(), AutTncActivity.class);
                                intent.putExtra("orderId", result);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getContext(), AutTradedDetailActivity.class);
                                intent.putExtra("orderId", result);
                                startActivity(intent);
                            }
                        });
                    } else {//否则是收款订单  或者分期订单  预授权结算后变成普通订单
                        searchOrder(result);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    //查询订单号
    private void searchOrder(String orderId) {

        model.getCollectionBillDetail(orderId, () -> {
            Intent intent = new Intent(getContext(), CollAndInstallDetailActivity.class);
            intent.putExtra("orderId", orderId);
            startActivity(intent);
        });
    }

    /**
     * 申请二维码扫描需要的权限
     */
    @SuppressLint("CheckResult")
    private void requestScanPermission() {
        permissions.requestEach(Manifest.permission.CAMERA).subscribe(permission -> {
            if (permission.granted) {
                scanCode();
            } else if (permission.shouldShowRequestPermissionRationale) {
                Toast.makeText(getContext(), "扫描二维码需要相机权限!", Toast.LENGTH_SHORT).show();

            } else {
                Uri packageURI = Uri.parse("package:" + getActivity().getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);

            }
        });
    }

    //开始扫描二维码
    private void scanCode() {
        Intent scanIntent = new Intent(getActivity(), ScanActivity.class);
        startActivityForResult(scanIntent, SCAN_CODE);
    }

    //更新ui
    public void updateUi(String content) {
        if (getActivity() == null) {
            return;
        }
        if (content != null) {
            Log.d(TAG, "showNoticeDialog: 获取到标题信息" + content);
            NoticeBean bean = new NoticeBean();
            bean.setContent(content);
            model.noticeBeans.set(bean);
            //将消息通知保存到本地
            Gson gson = new Gson();
            String str = gson.toJson(model.noticeBeans.get(), new TypeToken<NoticeBean>() {
            }.getType());
            ISharedPreference.getInstance(getActivity().getApplication()).saveNoticeStr(str);
        }
    }
}
